import { _decorator, Button, CCInteger, Label, Node, Sprite, SpriteAtlas, tween } from 'cc';
import { UIComponent } from '../../../../Framework/Scripts/Managers/UIComponent';
import { AbNames, EventMsgKes } from '../../Config/ResConfig';
import { SceneMgr } from '../../../../Framework/Scripts/Managers/SceneMgr';
import { UIMgr, UIType } from '../../../../Framework/Scripts/Managers/UIMgr';
import { Respones, RewardType } from '../../Config/GameCfg';
import { ResManager } from '../../../../Framework/Scripts/Managers/ResManager';
import { GameTip } from '../../../../Framework/Scripts/Managers/TipMgr';
import { GetUserInfoRes } from '../../../AssetPackage/Props/Hall/GetUserInfo';
import { NativeMgr } from '../../../../Framework/Scripts/Engine/NativeMgr';
import { IChouJiangCfgRes, IChouJiangOptRes, ICJItem } from '../GamHall/GameHallProto';
const { ccclass, property } = _decorator;


/**
 * 幸运转盘,抽奖
 */
@ccclass('GameHD5_Ctr')
export class GameHD5_Ctr extends UIComponent {
    com: {};
    
    @property
    public duration: number = 3;

    @property(CCInteger)
    rewardTypeCount: number = 6;//转盘中奖品分区数量

    @property(CCInteger)
    rotatelotterySecs: number = 12;//转盘动画旋转次数

    @property(CCInteger)
    lotterySecs: number = 5;//抽奖动画持续时间

    indexs:number[] = [];   //抽奖的结果数组

    private _isLottery: boolean = false;//是否正在抽奖


    trunBgNode: Node;
    labprice1: Label;
    labprice5: Label;
    labQuan: Label;
    opt1: number;
    opt5: number;

    opts: number[]; //当前抽中奖奖励的索引数组
    btnCj1: Button;
    btnCj5: Button;

    isStop: boolean = true;
    price: number;
    btnLab: any;


    protected onLoad(): void {
        this.InitUI();
    }

    start() {
        this.InitData();
        this.setBgAni(0);
    }

    protected onDestroy(): void {
        this.unRegisterEvent();
    }

    private InitUI(){
        this.registerEvent();

        this.trunBgNode = this.ViewNode('spDi/spMid');
        this.labprice1 = this.ViewComponent('spR/labPrice',Label);
        this.labprice5 = this.ViewComponent('spL/labPrice',Label);
        this.labQuan = this.ViewComponent('spBg/lab',Label);

        this.AddButtonListener('btnBack',this,this.OnBtnCloseClick1);
        this.AddButtonListener('spL',this,this.onBtnLClick);
        this.AddButtonListener('spR',this,this.onBtnRClick);
        this.AddButtonListener('Label',this, this.onShowViewClick);

        this.btnCj1 = this.ViewComponent('spR',Button);
        this.btnCj5 = this.ViewComponent('spL',Button);
        this.btnLab = this.ViewComponent('Label',Button);
    }

    private InitData(){
        this.opts = [];
        this.setCjBtnsStatus(true);

        globalThis.gameMgr._GameHallMsg.GetHD5_PrizeDrawCfgReq();
        this.getUserInfo();
    }

    private registerEvent(){
        globalThis.gameMgr._eventTarget.on(EventMsgKes.msgGetHD5_PrizeDrawListRes,this.onPrizeDrawListRes,this);
        globalThis.gameMgr._eventTarget.on(EventMsgKes.msgGetUserInfoRes,this.onGetUserInfoRes,this);
        globalThis.gameMgr._eventTarget.on(EventMsgKes.msgGetHD5_PrizeDrawOptRes,this.onPrizeDrawOptRes,this);
        
    }

    private unRegisterEvent(){
        globalThis.gameMgr._eventTarget.off(EventMsgKes.msgGetHD5_PrizeDrawListRes,this.onPrizeDrawListRes,this);
        globalThis.gameMgr._eventTarget.off(EventMsgKes.msgGetUserInfoRes,this.onGetUserInfoRes,this);
        globalThis.gameMgr._eventTarget.off(EventMsgKes.msgGetHD5_PrizeDrawOptRes,this.onPrizeDrawOptRes,this);
    }

    //设置抽奖按钮的点击状态 status = false 为禁用
    private setCjBtnsStatus(status: boolean){
        this.btnCj1.interactable = status;
        this.btnCj5.interactable = status;
        this.btnLab.instantiate = status;

        console.log('========setCjBtnsStatus===========', this.btnLab.instantiate);
    }

    public OnBtnCloseClick1(): void{
        if(!this.isStop){
            GameTip.inst.showTip('请等待抽奖结束！');
            return;
        }

        if(this.closeView && this.closeView.abName && this.closeView.path){
            UIMgr.inst.ShowUIView(this.closeView.abName, this.closeView.path,UIType.Full); 
        }else{
            SceneMgr.inst.showHall();
        }
    }

    private getUserInfo(){
        globalThis.gameMgr._GameHallMsg.GetUserInfoReq();
    }

    public setCloseView(abName: string, path:string){
        this.closeView.abName = abName;
        this.closeView.path = path;
    }

    private onSendOpt(opt: number,free: number = 1){
        if(!this.isStop){
            return;
        }
        this.isStop = false;
        globalThis.gameMgr._GameHallMsg.GetHD5_PrizeDrawOptReq(opt,free);
        this.setCjBtnsStatus(false);
    }

    //显示扣费
    private showCostPrice(opt: number){
        //显示扣钱
        let cost = opt*this.price;
        let have = parseInt(this.labQuan.string);
        console.log('============显示扣钱============',have,cost);
        if(have >= cost){
            this.labQuan.string = (have - cost).toString()
        }
    }

    //5连抽
    private onBtnLClick(btn: Button){
        this.onSendOpt(this.opt5);
        this.showCostPrice(this.opt5);
    }

    //单抽
    private onBtnRClick(btn: Button = null){
        this.onSendOpt(this.opt1);
        this.showCostPrice(this.opt1);
    }

    //点击看视频，视频结束，执行 onBtnRClick
    private onShowViewClick(){
        console.log('========onShowViewClick==============',this.isStop);
        if(!this.isStop){
            return;
        }
        NativeMgr.inst.seeView(()=>{
            this.onSendOpt(this.opt1,2);
        })
    }

    /**
     * 抽奖
     * @param index 
     * @returns 
     */
    private onWheelRun(index:number = 0 ,callback:Function = null){
        console.log('============onWheelRun==============',index);
        if (this._isLottery) {
            // console.log(`<onGoLotteryEvent> 正在抽奖请等待此轮抽奖结束`);
            return;
        }
        // console.log(`<onGoLotteryEvent> `);
        this._isLottery = true;

        // // 随机确定奖品分区
        // let index = Math.floor(Math.random() * this.rewardTypeCount);

        // 过场动作 顺时针转
        let targetAngle = -this.rotatelotterySecs * 360 + index * (360 / this.rewardTypeCount);
        // console.log(`<onGoLotteryEvent> 转盘角度之前: ${this.trunBgNode.angle}`);
        this.trunBgNode.angle %= 360;
        // console.log(`<onGoLotteryEvent> 转盘角度之后: ${this.trunBgNode.angle}`);
        // console.log(`<onGoLotteryEvent> index: ${index} ,旋转角度： ${index * (360 / this.rewardTypeCount)}`);

        // 过场动作+缓入缓出
        if (this.trunBgNode) {
            tween(this.trunBgNode)
                .target(this.trunBgNode)
                .to(this.lotterySecs, { angle: targetAngle }, { easing: "cubicInOut" })
                .delay(0.5)
                .call(() => {
                    this._isLottery = false;
                    // director.emit(EventMsgKes.hd_choujiang, { reward: index });
                    callback && callback();
                })
                .start();
        }
    }

    //抽奖配置返回
    private onPrizeDrawListRes(data: IChouJiangCfgRes){
        console.log('===========onPrizeDrawListRes==========');
       let atals = ResManager.inst.getAsset(AbNames.GameHall,'Atals/GameHall',SpriteAtlas) as SpriteAtlas;
        let children = this.trunBgNode.children;
        if(this.hasProInObj(data,'rewards')){
            for (let i = 0; i < data.rewards.length; i++) {
                let cfg:ICJItem = data.rewards[i];
                let node = children[i];
                let sf = null;
                let des = "";
                if(cfg.rewardType === RewardType.TYpe_QiuNum){
                    sf = atals.getSpriteFrame('GameHall_top_icon');
                    des = "球币x";
                }else if(cfg.rewardType === RewardType.Type_Quan){
                    sf = atals.getSpriteFrame('GameMRTZ_icon');
                    des = "抽奖券x";
                }
                if(sf){
                    node.getComponentInChildren(Sprite).spriteFrame = sf; 
                }
                node.getComponentInChildren(Label).string = des + cfg.rewardNum; 
            }
        }
        if(this.hasProInObj(data,'price')){
            this.price = data.price;
            if(this.hasProInObj(data,'optNum1')){
                this.labprice1.string = (data.price * data.optNum1).toString();
                this.opt1 = data.optNum1;
            }
            if(this.hasProInObj(data,'optNum5')){
                this.labprice5.string = (data.price * data.optNum5).toString();
                this.opt5 = data.optNum5;
            }
        }
    }

    private onGetUserInfoRes(data: GetUserInfoRes){
        if(this.hasProInObj(data,'userInfo')){
            this.labQuan.string = data.userInfo.ticket.toString();
        }
    }

    private onChoujinagOpt(){
        console.log('========onChoujinagOpt ===========',this.opts);
        if(this.opts.length <= 0){ //当前轮抽奖结束
            this.setCjBtnsStatus(true);
            console.log('========当前轮抽奖结束 ===========');
            this.isStop = true;
            //更新用户数数据
            this.getUserInfo();
            // end 
            return;
        }

        let idx = this.opts.shift();
        this.onWheelRun(idx - 1,()=>{
            this.onChoujinagOpt();
        });
    }

    //抽奖操作返回
    private onPrizeDrawOptRes(data: IChouJiangOptRes){
        console.log('=====onPrizeDrawOptRes==========',JSON.stringify(data));
        // this.isStop = true;
        if(this.hasProInObj(data,'code')){
            let code = data.code;
            if(code === Respones.QUAN_NAN){ //抽奖券不足
                GameTip.inst.showTip('抽奖券数量不足！');
                this.setCjBtnsStatus(true);
                this.isStop = true;
            }else if(code === Respones.FREE_COUNT_NAN){ 
                GameTip.inst.showTip('今日免费看广告次数使用完毕！');
                this.setCjBtnsStatus(true);
                this.isStop = true;
            }else if(code === Respones.OK){ //成功
                if(this.hasProInObj(data,'idxs')){
                    this.opts = data.idxs;
                    console.log('=====onPrizeDrawOptRes1==========', this.opts);
                        this.onChoujinagOpt();
                }
            }
        }
    }
}